import whiteList from "./pre-defined/white-list";
import { HttpError, Next } from "koa";
import { isUndefined, canUse } from "mmb";
import { AppCTX } from "../types/koaExtend";

export default async (ctx: AppCTX, next: Next) => {
  const reqUrl = ctx.request.url;
  if (
    whiteList.errHandler.findIndex((item) => reqUrl.startsWith(item)) === -1
  ) {
    try {
      await next();
      if (
        !ctx.response.is("application/octet-stream") &&
        !ctx.response.is("text/csv")
      ) {
        if (canUse(ctx.body)) {
          ctx.body = {
            success: isUndefined(ctx.body.success) ? true : ctx.body.success,
            code: isUndefined(ctx.body.success) ? "0" : ctx.body.code,
            data: ctx.body,
          };
        } else {
          ctx.status = 404;
          ctx.body = {
            success: true,
            code: "0",
            data: null,
          };
        }
      }
    } catch (err) {
      console.error(`---err---${ctx.state.trackingId}::`, err);
      ctx.body = {
        success: false,
        code: isUndefined(err.code) ? "500" : err.code,
        msg: err.message,
        data: null,
      };
      if (canUse(err.message)) {
        ctx.body.msg = err.message;
      }
      if (canUse(err.statusCode)) {
        ctx.res.statusCode = err.statusCode;
      }
      if (ctx.res.statusCode >= 400) {
        ctx.body.code = `${ctx.res.statusCode}`
      }
    }
  } else {
    await next();
  }
};
